<template>
  <div v-bind="$attrs" class="pf-con" >
    <a-form :form="form" @submit="handleSubmit" :layout="formConfig_.layout" :labelCol="formConfig_.labelCol"
      :labelAlign="formConfig_.labelAlign"
      :wrapperCol="formConfig_.wrapperCol">

      <a-row :key="'row-' + rowitem + rowindex" v-for="(rowitem, rowindex) in rowInfo"  v-bind="formConfig_.rowAttr || {}">
        <a-col :key="'col-' + item + colindex" v-for="(item, colindex) in rowitem"
        v-bind="getColAttr(item)"  >
        <!-- :span="isMonoRow(item) === true ? getColSpan(itemList_[item]): getColSpan1(rowitem, colindex)" -->
        <!-- v-bind="itemList_[item].colAttr || {}" -->
           <!-- :span="isMonoRow(item) === true ? 24 : aColSpan" -->
          <!-- {{rowInfo}}-- {{item}} -- {{ getColAttr(item)}} -->
          <a-form-item :id="itemList_[item].key" :key="itemList_[item].key" :label="itemList_[item].cnName" v-bind="itemList_[item].formItemAttr || {}">

            <a-input v-bind="itemList_[item].itemAttr || {}" v-if="itemList_[item].type === 'input'" v-decorator="[
              itemList_[item].enName,
              isRequire(itemList_[item])
            ]" @change="(e)=>{handleSelectChange(item,itemList_[item].enName,e.target.value)}"/>

            <a-select v-bind="itemList_[item].itemAttr || {}" v-if="itemList_[item].type === 'select'" v-decorator="[
              itemList_[item].enName,
              isRequire(itemList_[item])
            ]" @change="(...args)=>{handleSelectChange(item,itemList_[item].enName,...args)}">
              <a-select-option :key="optItem.cnName + optIndex"
                v-for="(optItem, optIndex) in itemList_[item].optionList" :value="optItem.enName" v-bind="{...optItem}">
                {{ optItem.cnName }}
              </a-select-option>

            </a-select>
            <a-checkbox-group v-bind="itemList_[item].itemAttr || {}" v-if="itemList_[item].type === 'checkboxGroup'"
              v-decorator="[
                itemList_[item].enName,
                isRequire(itemList_[item])
              ]" :options="itemList_[item].optionList"  @change="(...args)=>{handleSelectChange(item,itemList_[item].enName,...args)}"/>

            <a-textarea v-bind="itemList_[item].itemAttr || {}" v-if="itemList_[item].type === 'textarea'" v-decorator="[
              itemList_[item].enName,
              isRequire(itemList_[item])
            ]" @change="(e)=>{handleSelectChange(item,itemList_[item].enName,e.target.value)}" />
            <a-radio-group v-bind="itemList_[item].itemAttr || {}" v-if="itemList_[item].type === 'radioGroup'"
              v-decorator="[
                itemList_[item].enName,
                isRequire(itemList_[item])
              ]" @change="(e)=>{handleSelectChange(item,itemList_[item].enName,e.target.value)}">
              <a-radio-button :key="optItem.cnName + optIndex" v-for="(optItem, optIndex) in itemList_[item].optionList"
                :value="optItem.enName">
                {{ optItem.cnName }}
              </a-radio-button>
            </a-radio-group>

            <slot :name="itemList_[item].enName" :value="itemList_[item].value"
              :itemData="{ attr: itemList_[item].itemAttr || {}, value: itemList_[item].value }"
              v-if="itemList_[item].type === 'custom'"></slot>
            <div v-bind="itemList_[item].itemAttr || {}" v-if="itemList_[item].type === 'label'">
              {{ itemList_[item].value }}
            </div>

            <InputRange :value="itemList_[item].value" v-bind="itemList_[item].itemAttr || {}" v-if="itemList_[item].type === 'inputRange'" v-decorator="[
                itemList_[item].enName,
                isRequire(itemList_[item])
              ]"></InputRange>

            <a-date-picker v-bind="itemList_[item].itemAttr || {}" v-if="itemList_[item].type === 'datePicker'" v-decorator="[
                itemList_[item].enName,
                isRequire(itemList_[item])
              ]" @change="(...args)=>{handleSelectChange(item,itemList_[item].enName,...args)}"/>
            <a-range-picker v-bind="itemList_[item].itemAttr || {}" v-if="itemList_[item].type === 'rangePicker'" v-decorator="[
                itemList_[item].enName,
                isRequire(itemList_[item])
              ]" @change="(...args)=>{handleSelectChange(item,itemList_[item].enName,...args)}"/>

              <Cascader :optionsList="itemList_[item].optionList" :value="itemList_[item].value" :itemAttr="itemList_[item].itemAttr" v-bind="itemList_[item].itemAttr || {}" v-if="itemList_[item].type === 'cascader'"   @change="(...args)=>{handleSelectChange(item,itemList_[item].enName,...args)}" @search="(...args)=>{handleSelectChange(item,itemList_[item].enName,...args)}"></Cascader>
              <!-- <Cascader :optionsList="itemList_[item].optionList" :itemAttr="itemList_[item].itemAttr" v-bind="itemList_[item].itemAttr || {}" v-if="itemList_[item].type === 'cascader'" v-decorator="[
                itemList_[item].enName,
                isRequire(itemList_[item])
              ]"  @change="(...args)=>{handleSelectChange(item,itemList_[item].enName,...args)}" @search="(...args)=>{handleSelectChange(item,itemList_[item].enName,...args)}"></Cascader> -->
              <RadioGroup :optionsList="itemList_[item].optionList"  :itemAttr="itemList_[item].itemAttr"  v-if="itemList_[item].type === 'radioGroupHelp'" v-decorator="[
                itemList_[item].enName,
                isRequire(itemList_[item])
              ]"></RadioGroup>

              <!-- <ImgGroup :optionsList="itemList_[item].optionList"  v-bind="itemList_[item].itemAttr || {}" v-if="itemList_[item].type === 'imgGroup'" v-decorator="[
                itemList_[item].enName,
                isRequire(itemList_[item])
              ]"></ImgGroup> -->
              <p-ImgGroup  v-if="itemList_[item].type === 'imgGroup'"  v-bind="itemList_[item] || {}"  :showHelp="false"></p-ImgGroup>

              <TextGroup :optionsList="itemList_[item].optionList" @textGroupEvent="textGroupEvent" v-bind="itemList_[item].itemAttr || {}" v-if="itemList_[item].type === 'textGroup'" v-decorator="[
                itemList_[item].enName,
                isRequire(itemList_[item])
              ]"></TextGroup>


          </a-form-item>

        </a-col>

      </a-row>

    </a-form>
  </div>
</template>

<script>
// import UUID from './../../utils/uuid'
// const formKey_queryForm =  UUID()
// import moment from 'moment';
import InputRange from './PageFormItem/InputGroup.vue'
import Cascader from './PageFormItem/cascader.vue'
import ImgGroup from './PageFormItem/ImgGroup.vue'
import TextGroup from './PageFormItem/TextGroup.vue'
import RadioGroup from './PageFormItem/RadioGroup.vue'
export default {
  name: 'PageForm',
  components:{InputRange,Cascader,ImgGroup,TextGroup,RadioGroup},
  props: {
    // 此属性为必传字段  为表单设置一个key  在 @utils/
    formKey:{require:true, type:String},
    formConfig: {
      type: Object, default: () => {
        return {
          columnCount: 3,
          layout: 'horizontal',
          labelCol: { span: 6 },
          wrapperCol: { span: 18 },
        }
      }
    },
    itemList: { type: Array, default: () => [] },
    formEvent: { type: Function, default: () => null }
  },
  data() {
    return {
      // formKey_form:formKey_queryForm,
      rowColumnNum: 24,
      formConfig_: {
        columnCount: 3,
        layout: 'horizontal',
        labelCol: { span: 6 },
        wrapperCol: { span: 18 },
        rowAttr:{
          // type:'',
          // justify:'',
          // gutter:'',
          // align:'',
        },
        celAttr:{
          // flex:'',
          // offset:'',
          // order:'',
          // pull:'',
          // push:'',
          // span:'',
          // xxl:{},
        }
      },
      itemList_: [],
      formObjData: {},
      rowInfo: [],
      form: {},
      // 用于返回校验结果
      checkRes: false
    }
  },
  watch: {
    formConfig: {
      handler(val) {
        if (Object.prototype.toString.call(val) === '[object Object]') {
          Object.keys(val).forEach(key => {
            this.formConfig_[key] = val[key]
          })
        }
        // console.log('formConfig watch ==>',val);
      },
      deep: true,
      immediate: true
    },
    itemList: {
      handler(val) {
        if (Object.prototype.toString.call(val) === '[object Array]') {
          const tempArr = []
          this.itemList_ = val
            for (let i = 0; i < val.length; i++) {
              if(!this.itemList_[i]['key']){
                const item = val[i];
                const dataKey = this.getDataKey(JSON.stringify(item))
                this.itemList_[i]['key'] = dataKey
              }
            }
        }
        // console.log('itemList watch ==>',val,this.itemList_);
      },
      deep: true,
      immediate: true
    },
  },
  computed: {
    aColSpan() {
      const res = this.rowColumnNum / this.formConfig.columnCount
      return res
    }
  },
  created() {
    this.form = this.$form.createForm(this, {
      onFieldsChange: (_, changedFields) => {
        // console.log('onFieldsChange===>',_, changedFields);
        this.$emit('change', changedFields);
      },

      onValuesChange: (_, values) => {
        // {date61: '371'}
        const key = Object.keys(values)[0]
        this.$nextTick(() => {
          const tempObj = this.formObjData[key]
          if (tempObj.isChangeEvent && tempObj.isChangeEvent === true) {
            const valObj = {
              formKey:this.formKey,
              values
              // values: this.dataFormat(values,tempObj)
            }
            this.formEvent('update', valObj)
          }
          // console.log('onValuesChange===>',_,values,key, this.formObjData[key]);
        })
      },
    });
  },
  mounted() {
    this.getRowAndColumn()
    this.$nextTick(() => {
      this.getFormObj()
    })
    // window['pageForm'] =  this
  },
  methods: {

    getColAttr(dataIndex){
      let res= {}
      const colItem = this.itemList_[dataIndex]
      const {celAttr} = this.formConfig_
      const isMono = this.isMonoRow(dataIndex)
      if(isMono===true){
        // res = {...celAttr,span:24,...colItem.itemAttr && colItem.itemAttr.celAttr}
        res = {span:24,...colItem.itemAttr && colItem.itemAttr.celAttr}
        // console.log('getColAttr===>',colItem.cnName,colItem.itemAttr,celAttr,res);
      } else {
        res = {...celAttr,...colItem.celAttr}
      }

      return res
    },

    handleProvinceChange(iten,values_,item){
      const valObj = {
        formKey:this.formKey,
        values:{[iten.enName]:values_}
      }
      this.formEvent('update', valObj)
      // console.log('handleProvinceChange===>',iten,values_,item);
    },
    getRowAndColumn() {
      const tempDataSize = this.itemList_.length
      if (tempDataSize > 0) {
        const columnCount = this.formConfig_.columnCount
        let rowCount = Math.floor(tempDataSize / columnCount)
        if(columnCount==0){
          rowCount = Math.floor(tempDataSize / 2)
        }
        if (tempDataSize % columnCount > 0) {
          rowCount = rowCount + 1
        }
        this.itemList_.forEach(item => {
          const { monoRow } = item
          if (monoRow && monoRow === true) {
            rowCount = rowCount + 1
          }
        })
        const resArr = []
        let tempNum = 0
        for (let i = 0; i < rowCount; i++) {
          const tempArr = []
          if (this.isMonoRow(tempNum)) {
            if (tempNum < tempDataSize) {
              tempArr.push(tempNum)
            }
            tempNum++
          } else {
            for (let ic = 0; ic < columnCount; ic++) {
              if (tempNum <= tempDataSize - 1) {
                tempArr.push(tempNum)
              }
              tempNum++
            }
          }

          resArr.push(tempArr)
        }

        this.rowInfo = resArr
        // console.log('this.rowInfo===>',this.rowInfo);
      }
    },
    isMonoRow(dataIndex) {
      const { monoRow } = this.itemList_[dataIndex] || {}
      let res = false
      if (monoRow && monoRow === true) {
        res = true
      }
      return res
    },

    getColSpan(itemData) {
      let colSize = 24
      const {pull=0,push=0} = itemData.colAttr || {}
      colSize = colSize - pull - push
      return colSize
    },

    getColSpan1(item,colindex){
      // itemList_
      let res = 0
      let tempSize = 0
      for (let index = 0; index < item.length; index++) {
        const element = item[index];
        const {monoRow,colAttr} = this.itemList_[element]
        const {pull,push} = colAttr || {}
        if(monoRow === true){
          continue;
        }
        if(Object.prototype.toString.call(pull)==='[object Number]'){
          tempSize +=pull
        }
        if(Object.prototype.toString.call(push)==='[object Number]'){
          tempSize +=push
        }
      }
      //this.rowColumnNum / this.formConfig.columnCount
      res =  (this.rowColumnNum - tempSize) / this.formConfig.columnCount
      // console.log('getColSpan1===>',res,this.rowColumnNum,tempSize,this.formConfig.columnCount,'|',item,this.rowInfo);
      return Math.floor(res)
    },

    getFormObj() {
      const tempObj = {}
      this.itemList_.forEach(item => {
        tempObj[item.enName] = { ...item }
        // this.form.setFieldsValue({[item.enName]:item.value})
      })
      this.formObjData = tempObj
    },
    isRequire(itemInfo) {
      const { isRequire, value, cnName } = itemInfo
      // initialValue:'初始化值'
      const res = { rules: [], initialValue: value }
      // { rules: [{ required: true, message: 'Please select your country!' }] },
      if (Object.prototype.toString.call(isRequire) === '[object Boolean]') {
        res.rules = [{ required: true, message: `${cnName} 值不能为空` }]
      }
      if (Object.prototype.toString.call(isRequire) === '[object Array]') {
        res.rules = isRequire
      }
      // console.log('isRequire===>',cnName,res);
      return res
    },

    handleSelectChange(index, key ,value){
      const temp = {[key]:value}
      this.itemList_[index].value = value?JSON.parse(JSON.stringify(value)):value
      console.log('handleSelectChange====>',temp);
      this.form.setFieldsValue(temp);
    },
    /**
     * 设置单个表单元素的值
     * @param {object} data {fieldName:fieldValue}
     */
    setFieldValue(data) {
      this.form.setFieldsValue(data)
    },
    /**
     * 获取表单元素的值
     * @param {*} fieldNames
     */
    getFieldsValue(fieldNames){
      this.form.getFieldsValue(fieldNames)

    },
    /**
     * 动态设置指定下拉框的下拉列表数据
     * @param {object} data { isCover: true, fieldName: Array<OptionItemType>}  OptionItemType的值参照说明文档  isCover 表示是否覆盖原来的值，默认值为true; true 表示覆盖  false 表示不覆盖
     */
    setOptionListData(data) {
      if (Object.prototype.toString.call(data) !== '[object Object]') {
        console.log('请检查传入的参数是否正确');
        return false
      }
      const { isCover = true, ...args } = data
      const key = Object.keys(args)[0]
      const listData = data[key]
      const tempDataList = JSON.parse(JSON.stringify(this.itemList_))
      tempDataList.forEach((item, index) => {
        const { enName } = item
        if (enName === key) {
          if (isCover) {
            this.itemList_[index].optionList = listData
          } else {
            this.itemList_[index].optionList = [...this.itemList_[index].optionList, ...listData]
          }
        }
      })
    },
    /**
     * 表单校验
     * @param {*} e
     */
    handleSubmit(e) {
      // e.preventDefault();
      this.form.validateFields((err, values) => {
        if (!err) {
          this.checkRes = true
          // console.log('Received values of form: ', values);
          const valObj = {
            formKey:this.formKey,
            values
          }
          this.formEvent('submit', valObj)
        } else {
          this.checkRes = false
        }
      });
      // console.log('查看示例===》', this.form);
    },
    getDataKey(dataStr){
      return this.UUID('MDUUID',dataStr)
    },
    textGroupEvent(label){
      this.formEvent('textEvent', label)
    }
  },
}
</script>

<style>
.pf-con {
  width: 100%;
  height: 100%;
}
</style>
